"use client"
import { Tabs, Toast } from 'antd-mobile'
import { useState, useMemo } from 'react'
import styles from '@/app/home/editPage/editPage.module.scss'
import NumberPad from '@/components/pageComponents/home/editPageCom/NumberPad'
import Tags from '@/components/pageComponents/home/editPageCom/Tags'
import {useEditPageStore, BearStore} from '@/store/useEditPageStore'
import { cFetch } from '@/lib/Http'
import useRequireAuth from '@/hooks/useRequireAuth'
export default function(){
  useRequireAuth()
  
  const {curTagType, setCurTagType} = useEditPageStore() as BearStore
  const handTabChange = (key: string) => {
    setCurTagType(key as TagType)
  }
  const [expensesTagId, setExpensesTagId] = useState<number>()
  const [incomeTagId, setIncomeTagId] = useState<number>()
  const signValue = useMemo(()=>{
    return curTagType === 'expenses' ? expensesTagId : incomeTagId
  },[curTagType,expensesTagId,incomeTagId])

  const handleSubmit = async (value: Partial<Item>) => {
    if(signValue === undefined){
      Toast.show({ icon: 'fail', content: '请选择标签', })
      return
    }
    let result
    await cFetch.post('/item', { ...value, tag_id: signValue, kind: curTagType }, { _autoLoading: true }).then(res=>{
      Toast.show({ icon: 'success', content: '添加成功'})
      result = true
    }).catch(()=>{
      Toast.show({ icon: 'fail', content: '保存失败', })
      result = false
    })
    return result
  }
  return <div className={styles.editPage}>
    <section className={styles.tagsBox}>
      <Tabs activeKey={curTagType} onChange={handTabChange}>
        <Tabs.Tab title='支出' key='expenses'>
          <Tags kind="expenses" setCurTag={ setExpensesTagId }/>
        </Tabs.Tab>
        <Tabs.Tab title='收入' key='income'>
          <Tags kind="income" setCurTag={ setIncomeTagId }/>
        </Tabs.Tab>
      </Tabs>
    </section>
    <NumberPad submit={handleSubmit}/>
  </div>
}